import "package:ct_pa_majordomo/pages/mine/online_pay/api.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import 'package:flutter/material.dart';
import 'package:ct_pa_majordomo/config/theme_vars.dart';
import 'package:ct_pa_majordomo/pages/widgets/menu_block.dart';
import 'package:ct_pa_majordomo/pages/mine/online_pay/state/online_pay_state.dart';

import 'package:ct_pa_majordomo/router/keys.dart';
import 'package:ct_pa_majordomo/utils/stacker.dart';
import "package:flutter_easyloading/flutter_easyloading.dart";

class OnlinePayPage extends StatefulWidget {
  const OnlinePayPage({super.key});

  @override
  State<OnlinePayPage> createState() => _OnlinePayPageState();
}

class _OnlinePayPageState extends State<OnlinePayPage> {
  bool _isEnterprise = false;
  bool _isAgreed = false;
  final OnlinePayState _state = OnlinePayState();
  
  // 新增审核状态相关变量
  bool _isLoading = true;
  bool _isInAudit = false; // 是否在审核中（提交状态）
  bool _isDraft = false; // 是否是草稿状态
  
  @override
  void initState() {
    super.initState();
    _loadPaymentInfo();
  }

  // 获取支付申请信息
  Future<void> _loadPaymentInfo() async {
    try {
      final response = await onlinePayApi.getInfo();
      
      if (response['data'] == null) {
        // 返回数据为空，表示未申请
        setState(() {
          _isInAudit = false;
          _isDraft = false;
          _isLoading = false;
        });
      } else {
        // 有数据，检查审核状态
        final apiData = response['data'] as Map<String, dynamic>;
        final auditStatus = apiData['auditStatus']?.toString();
        final accountType = apiData['accountType']?.toString();
        
        // 更新状态管理中的数据
        _state.updateFromApiData(apiData);
        
        // 调试信息：验证数据是否正确更新
        print('账户类型: $accountType');
        print('审核状态: $auditStatus');
        if (accountType == '1') {
          print('个人数据已更新: ${_state.person}');
        } else if (accountType == '2') {
          print('企业数据已更新: ${_state.company}');
        }
        
        setState(() {
          _isInAudit = auditStatus == '0'; // 提交状态
          _isDraft = auditStatus == '99'; // 草稿状态
          // 根据accountType设置企业/个人类型
          _isEnterprise = accountType == '2';
          _isLoading = false;
        });
      }
    } catch (e) {
      print('获取支付信息失败: $e');
      setState(() {
        _isLoading = false;
      });
    }
  }

  bool _canSubmit() {
    // 如果正在审核中（提交状态），不允许提交
    if (_isInAudit) return false;
    
    if (_isEnterprise) {
      return _state.canSubmitCompany(_isAgreed);
    } else {
      return _state.canSubmitPerson(_isAgreed);
    }
  }

  Future<void> _submit() async {
    Map<String, dynamic> data = _isEnterprise ? _state.company : _state.person;
    EasyLoading.show();
    try {
      await onlinePayApi.save(data);
      // await onlinePayApi.draft(data);
      EasyLoading.showSuccess("提交成功");
      Stacker.pop(true);
    } catch (e) {
      print(e);
      EasyLoading.dismiss();
    }
  }

  @override
  Widget build(BuildContext context) {
    // 如果正在加载，显示loading
    if (_isLoading) {
      return NormalScaffold(
        title: "开通线上支付",
        child: const Center(
          child: CircularProgressIndicator(),
        ),
      );
    }
    
    return NormalScaffold(
      title: "开通线上支付",
      bottom: PreferredSize(
        preferredSize: const Size.fromHeight(56),
        child: Container(
          width: double.infinity,
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          color: Colors.white,
          child: SegmentedButton<bool>(
            segments: const [
              ButtonSegment<bool>(
                value: false,
                label: Text('个人'),
              ),
              ButtonSegment<bool>(
                value: true,
                label: Text('企业'),
              ),
            ],
            selected: {_isEnterprise},
            onSelectionChanged: _isInAudit ? null : (Set<bool> newSelection) {
              setState(() {
                _isEnterprise = newSelection.first;
              });
            },
            style: ButtonStyle(
              backgroundColor: WidgetStateProperty.resolveWith<Color>(
                (Set<WidgetState> states) {
                  if (states.contains(WidgetState.disabled)) {
                    return Colors.grey.shade100;
                  }
                  if (states.contains(WidgetState.selected)) {
                    return ThemeVars.colorPrimary;
                  }
                  return Colors.white;
                },
              ),
              foregroundColor: WidgetStateProperty.resolveWith<Color>(
                (Set<WidgetState> states) {
                  if (states.contains(WidgetState.disabled)) {
                    return Colors.grey.shade400;
                  }
                  if (states.contains(WidgetState.selected)) {
                    return Colors.white;
                  }
                  return Colors.black;
                },
              ),
              side: WidgetStateProperty.resolveWith<BorderSide>(
                (Set<WidgetState> states) {
                  if (states.contains(WidgetState.disabled)) {
                    return BorderSide(color: Colors.grey.shade300);
                  }
                  return BorderSide(color: ThemeVars.colorPrimary);
                },
              ),
              shape: WidgetStateProperty.all(
                RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
            ),
          ),
        ),
      ),
      child: Stack(
        children: [
          Padding(
            padding: const EdgeInsets.only(bottom: 100),
            child: Column(
              children: [
                // 审核状态提示
                if (_isInAudit || _isDraft) _buildAuditStatusTip(),
                Expanded(
                  child: _isEnterprise ? _buildEnterpriseTab() : _buildPersonalTab(),
                ),
              ],
            ),
          ),
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.05),
                    blurRadius: 10,
                    offset: const Offset(0, -2),
                  ),
                ],
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Row(
                    children: [
                      Checkbox(
                        value: _isAgreed,
                        onChanged: (value) {
                          setState(() {
                            _isAgreed = value ?? false;
                          });
                        },
                      ),
                      Expanded(
                        child: GestureDetector(
                          onTap: () {
                            setState(() {
                              _isAgreed = !_isAgreed;
                            });
                          },
                          child: const Text(
                            '我已阅读并同意《支付服务协议》',
                            style: TextStyle(
                              color: ThemeVars.colorTextSec,
                              fontSize: 14,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 12),
                  SizedBox(
                    width: double.infinity,
                    height: 44,
                    child: ElevatedButton(
                      onPressed: _canSubmit() ? () {
                        _submit();
                      } : null,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: ThemeVars.colorPrimary,
                        foregroundColor: Colors.white,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                      ),
                      child: const Text(
                        '提交申请',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPersonalTab() {
    return ListView(
      padding: const EdgeInsets.all(ThemeVars.paddingPage),
      children: [
        MenuBlock(
          items: [
            MenuBlockItem(
              prefix: const Icon(Icons.info_outline),
              text: '基本信息',
              suffix: GestureDetector(
                onTap: () {
                  Navigator.pushNamed(
                    context,
                    Keys.ONLINE_PAY_BASIC_INFO,
                    arguments: {
                      "state": _state,
                      "onStateChanged": () => setState(() {}),
                      "isEnterprise": false,
                      "isReadOnly": _isInAudit, // 只有提交状态才只读
                    },
                  );
                },
                child: Text(
                  _state.isPersonBasicInfoCompleted ? '已完成' : '去填写',
                  style: TextStyle(
                    color: _state.isPersonBasicInfoCompleted 
                      ? Colors.black
                      : ThemeVars.colorTextTer,
                    fontWeight: _state.isPersonBasicInfoCompleted 
                      ? FontWeight.w500 
                      : FontWeight.normal,
                  ),
                ),
              ),
            ),
            MenuBlockItem(
              prefix: const Icon(Icons.photo_outlined),
              text: '身份证照片信息',
              suffix: GestureDetector(
                onTap: () {
                  Navigator.pushNamed(
                    context,
                    Keys.ONLINE_PAY_ID_CARD,
                    arguments: {
                      "state": _state,
                      "onStateChanged": () => setState(() {}),
                      "isEnterprise": false,
                      "isReadOnly": _isInAudit,
                    },
                  );
                },
                child: Text(
                  _state.isPersonIdCardCompleted ? '已完成' : '去填写',
                  style: TextStyle(
                    color: _state.isPersonIdCardCompleted 
                      ? Colors.black
                      : ThemeVars.colorTextTer,
                    fontWeight: _state.isPersonIdCardCompleted 
                      ? FontWeight.w500 
                      : FontWeight.normal,
                  ),
                ),
              ),
            ),
            MenuBlockItem(
              prefix: const Icon(Icons.store_outlined),
              text: '经营场所照片',
              suffix: GestureDetector(
                onTap: () {
                  Navigator.pushNamed(
                    context,
                    Keys.ONLINE_PAY_STORE_PHOTO,
                    arguments: {
                      "state": _state,
                      "onStateChanged": () => setState(() {}),
                      "isEnterprise": false,
                      "isReadOnly": _isInAudit,
                    },
                  );
                },
                child: Text(
                  _state.isPersonBusinessPlaceCompleted ? '已完成' : '去填写',
                  style: TextStyle(
                    color: _state.isPersonBusinessPlaceCompleted 
                      ? Colors.black
                      : ThemeVars.colorTextTer,
                    fontWeight: _state.isPersonBusinessPlaceCompleted 
                      ? FontWeight.w500 
                      : FontWeight.normal,
                  ),
                ),
              ),
            ),
            MenuBlockItem(
              prefix: const Icon(Icons.account_balance_outlined),
              text: '结算账户',
              suffix: GestureDetector(
                onTap: () {
                  Navigator.pushNamed(
                    context,
                    Keys.ONLINE_PAY_SETTLEMENT,
                    arguments: {
                      "state": _state,
                      "onStateChanged": () => setState(() {}),
                      "isReadOnly": _isInAudit,
                    },
                  );
                },
                child: Text(
                  _state.isPersonSettlementCompleted ? '已完成' : '去填写',
                  style: TextStyle(
                    color: _state.isPersonSettlementCompleted 
                      ? Colors.black
                      : ThemeVars.colorTextTer,
                    fontWeight: _state.isPersonSettlementCompleted 
                      ? FontWeight.w500 
                      : FontWeight.normal,
                  ),
                ),
              ),
            ),
          ],
        ),
        const SizedBox(height: 15),
        _buildNoticeCard(),
      ],
    );
  }

  Widget _buildEnterpriseTab() {
    return ListView(
      padding: const EdgeInsets.all(ThemeVars.paddingPage),
      children: [
        MenuBlock(
          items: [
            MenuBlockItem(
              prefix: const Icon(Icons.info_outline),
              text: '基本信息',
              suffix: GestureDetector(
                onTap: () {
                  Navigator.pushNamed(
                    context,
                    Keys.ONLINE_PAY_BASIC_INFO,
                    arguments: {
                      "state": _state,
                      "onStateChanged": () => setState(() {}),
                      "isEnterprise": true,
                      "isReadOnly": _isInAudit,
                    },
                  );
                },
                child: Text(
                  _state.isCompanyBasicInfoCompleted ? '已完成' : '去填写',
                  style: TextStyle(
                    color: _state.isCompanyBasicInfoCompleted 
                      ? Colors.black
                      : ThemeVars.colorTextTer,
                    fontWeight: _state.isCompanyBasicInfoCompleted 
                      ? FontWeight.w500 
                      : FontWeight.normal,
                  ),
                ),
              ),
            ),
            MenuBlockItem(
              prefix: const Icon(Icons.business_outlined),
              text: '营业执照照片',
              suffix: GestureDetector(
                onTap: () {
                  Navigator.pushNamed(
                    context,
                    Keys.ONLINE_PAY_BUSINESS_LICENSE,
                    arguments: {
                      "state": _state,
                      "onStateChanged": () => setState(() {}),
                      "isReadOnly": _isInAudit,
                    },
                  );
                },
                child: Text(
                  _state.isCompanyBusinessLicenseCompleted ? '已完成' : '去填写',
                  style: TextStyle(
                    color: _state.isCompanyBusinessLicenseCompleted 
                      ? Colors.black
                      : ThemeVars.colorTextTer,
                    fontWeight: _state.isCompanyBusinessLicenseCompleted 
                      ? FontWeight.w500 
                      : FontWeight.normal,
                  ),
                ),
              ),
            ),
            MenuBlockItem(
              prefix: const Icon(Icons.photo_outlined),
              text: '法人身份证照片',
              suffix: GestureDetector(
                onTap: () {
                  Navigator.pushNamed(
                    context,
                    Keys.ONLINE_PAY_ID_CARD,
                    arguments: {
                      "state": _state,
                      "onStateChanged": () => setState(() {}),
                      "isEnterprise": true,
                      "isReadOnly": _isInAudit,
                    },
                  );
                },
                child: Text(
                  _state.isCompanyIdCardCompleted ? '已完成' : '去填写',
                  style: TextStyle(
                    color: _state.isCompanyIdCardCompleted 
                      ? Colors.black
                      : ThemeVars.colorTextTer,
                    fontWeight: _state.isCompanyIdCardCompleted 
                      ? FontWeight.w500 
                      : FontWeight.normal,
                  ),
                ),
              ),
            ),
            MenuBlockItem(
              prefix: const Icon(Icons.description_outlined),
              text: '开户许可证照片',
              suffix: GestureDetector(
                onTap: () {
                  Navigator.pushNamed(
                    context,
                    Keys.ONLINE_PAY_ACCOUNT_LICENSE,
                    arguments: {
                      "state": _state,
                      "onStateChanged": () => setState(() {}),
                      "isReadOnly": _isInAudit,
                    },
                  );
                },
                child: Text(
                  _state.isCompanyAccountLicenseCompleted ? '已完成' : '去填写',
                  style: TextStyle(
                    color: _state.isCompanyAccountLicenseCompleted 
                      ? Colors.black
                      : ThemeVars.colorTextTer,
                    fontWeight: _state.isCompanyAccountLicenseCompleted 
                      ? FontWeight.w500 
                      : FontWeight.normal,
                  ),
                ),
              ),
            ),
            MenuBlockItem(
              prefix: const Icon(Icons.store_outlined),
              text: '经营场所照片',
              suffix: GestureDetector(
                onTap: () {
                  Navigator.pushNamed(
                    context,
                    Keys.ONLINE_PAY_STORE_PHOTO,
                    arguments: {
                      "state": _state,
                      "onStateChanged": () => setState(() {}),
                      "isEnterprise": true,
                      "isReadOnly": _isInAudit,
                    },
                  );
                },
                child: Text(
                  _state.isCompanyBusinessPlaceCompleted ? '已完成' : '去填写',
                  style: TextStyle(
                    color: _state.isCompanyBusinessPlaceCompleted 
                      ? Colors.black
                      : ThemeVars.colorTextTer,
                    fontWeight: _state.isCompanyBusinessPlaceCompleted 
                      ? FontWeight.w500 
                      : FontWeight.normal,
                  ),
                ),
              ),
            ),
            MenuBlockItem(
              prefix: const Icon(Icons.account_balance_outlined),
              text: '结算账户',
              suffix: GestureDetector(
                onTap: () {
                  Navigator.pushNamed(
                    context,
                    Keys.ONLINE_PAY_ENTERPRISE_SETTLEMENT,
                    arguments: {
                      "state": _state,
                      "onStateChanged": () => setState(() {}),
                      "isReadOnly": _isInAudit,
                    },
                  );
                },
                child: Text(
                  _state.isCompanySettlementCompleted ? '已完成' : '去填写',
                  style: TextStyle(
                    color: _state.isCompanySettlementCompleted 
                      ? Colors.black
                      : ThemeVars.colorTextTer,
                    fontWeight: _state.isCompanySettlementCompleted 
                      ? FontWeight.w500 
                      : FontWeight.normal,
                  ),
                ),
              ),
            ),
          ],
        ),
        const SizedBox(height: 15),
        _buildNoticeCard(),
      ],
    );
  }

  // 审核状态提示卡片
  Widget _buildAuditStatusTip() {
    String tipText;
    Color tipColor;
    IconData tipIcon;
    
    if (_isInAudit) {
      tipText = '线上支付已提交审核，暂时无法修改申请信息和切换账户类型';
      tipColor = Colors.orange;
      tipIcon = Icons.schedule_outlined;
    } else if (_isDraft) {
      tipText = '当前为草稿状态，可以继续完善申请信息';
      tipColor = Colors.blue;
      tipIcon = Icons.edit_outlined;
    } else {
      tipText = '申请信息提示';
      tipColor = Colors.grey;
      tipIcon = Icons.info_outline;
    }

    return Container(
      margin: const EdgeInsets.all(ThemeVars.paddingPage),
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        color: tipColor.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: tipColor.withOpacity(0.3),
        ),
      ),
      child: Row(
        children: [
          Icon(
            tipIcon,
            color: tipColor,
            size: 20,
          ),
          const SizedBox(width: 8),
          Expanded(
                          child: Text(
                tipText,
                style: TextStyle(
                  color: _isInAudit 
                      ? Colors.orange.shade700 
                      : _isDraft 
                        ? Colors.blue.shade700 
                        : Colors.grey.shade700,
                  fontSize: 14,
                ),
              ),
          ),
        ],
      ),
    );
  }

  Widget _buildNoticeCard() {
    return Container(
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '开通在线支付需知：',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 10),
          const Text('• 资金T+1日直达账户，免体现自动到账'),
          const SizedBox(height: 5),
          const Text('• 支付服务商将收取订单金额0.5%的交易费率'),
        ],
      ),
    );
  }
} 